import Vue from 'vue'
import router from '@/router'
import store from '@/store'
/**
 * 获取uuid
 */
export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth (key) {
  return JSON.parse(sessionStorage.getItem('permissions') || '[]').indexOf(key.replace(/:/g, '_')) !== -1 || false
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
  let res = []
  let temp = {}
  for (let i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (let k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

/**
 * 清除登录信息
 */
export function clearLoginInfo () {
  Vue.cookie.delete('token')
  store.commit('resetStore')
  router.options.isAddDynamicMenuRoutes = false
}
/* json 返回指定列 */
export function getParamValues (name, arr) {
  const ret = []
  for (var i = 0, len = arr.length; i < len; i++) {
    ret.push(arr[i][name])
  }
  return ret
}

/* Array 数组去重复项 */
export function unique (arr) {
  const result = []
  const hash = {}
  for (var i = 0, len = arr.length; i < len; i++) {
    if (!hash[arr[i]] && arr[i]) {
      result.push(arr[i])
      hash[arr[i]] = true
    }
  }
  return result
}
/* 截取指定内容的字符串 */
export function getCaption (obj, str) {
  var index = obj.indexOf(str)
  obj = obj.substring(index + 1, obj.length)
//  console.log(obj);
  return obj
}
